<template>
  <view class="my-page">
    <!-- 页面标题 -->
    <view class="page-header">
      <text class="page-title">我的</text>
      <text class="page-subtitle">个人中心</text>
    </view>

    <!-- 抽奖次数卡片 -->
    <view class="card lottery-card">
      <view class="lottery-header">
        <text class="lottery-title">🎯 我的抽奖次数</text>
        <button class="history-btn" @tap="showLotteryHistory">
          <text class="history-text">查看历史</text>
        </button>
      </view>
      <view class="lottery-content">
        <text class="lottery-count">{{ totalLotteryCount }}</text>
        <text class="lottery-unit">次</text>
      </view>
    </view>

    <!-- 功能菜单 -->
    <view class="card menu-card">
      <view class="menu-header">
        <text class="menu-title">🛠️ 功能菜单</text>
      </view>
      <view class="menu-list">
        <view class="menu-item" @tap="goToExchange">
          <view class="menu-icon">🎁</view>
          <text class="menu-text">免费兑换</text>
          <view class="menu-arrow-icon">›</view>
        </view>
        <view class="menu-item" @tap="goToOrderList">
          <view class="menu-icon">📦</view>
          <text class="menu-text">订单详情</text>
          <view class="menu-arrow-icon">›</view>
        </view>
        <view class="menu-item" @tap="goToAddressList">
          <view class="menu-icon">📍</view>
          <text class="menu-text">地址管理</text>
          <view class="menu-arrow-icon">›</view>
        </view>
      </view>
    </view>

    <!-- 兑换进度卡片 -->
    <view class="card progress-card">
      <view class="progress-header">
        <text class="progress-title">兑换进度</text>
        <text class="progress-desc">需要{{ requiredCount }}次抽奖次数</text>
      </view>
      
      <view class="progress-content">
        <view class="progress-bar">
          <view 
            class="progress-fill" 
            :style="{ width: progressPercentage + '%' }"
          ></view>
        </view>
        <view class="progress-text">
          <text class="current-count">{{ totalLotteryCount }}</text>
          <text class="separator">/</text>
          <text class="required-count">{{ requiredCount }}</text>
        </view>
      </view>
      
      <view class="progress-status">
        <text 
          class="status-text" 
          :class="canExchange ? 'can-exchange' : 'cannot-exchange'"
        >
          {{ canExchange ? '🎉 可以兑换啦！' : `还需要${requiredCount - totalLotteryCount}次` }}
        </text>
      </view>
    </view>

    <!-- 抽奖历史弹窗 -->
    <view class="lottery-modal" v-if="showHistoryModal" @tap="hideLotteryHistory">
      <view class="modal-content" @tap.stop>
        <view class="modal-header">
          <text class="modal-title">抽奖历史</text>
          <text class="modal-close" @tap="hideLotteryHistory">×</text>
        </view>
        <view class="modal-body">
          <view class="history-list" v-if="lotteryHistory.length > 0">
            <view class="history-item" v-for="(item, index) in lotteryHistory" :key="index">
              <view class="history-info">
                <text class="history-prize">{{ item.prize }}</text>
                <text class="history-time">{{ formatTime(item.time) }}</text>
              </view>
              <view class="history-status">
                <text class="prize-badge" :class="getPrizeClass(item.type)">{{ item.type }}</text>
              </view>
            </view>
          </view>
          <view class="empty-history" v-else>
            <text class="empty-text">暂无抽奖记录</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 兑换表单 -->
    <view class="card exchange-form-card" v-if="canExchange">
      <view class="form-header">
        <text class="form-title">📝 填写收货信息</text>
      </view>
      
      <view class="form-content">
        <view class="form-item">
          <text class="form-label">收货人姓名</text>
          <input 
            class="form-input" 
            v-model="exchangeForm.name" 
            placeholder="请输入收货人姓名"
            maxlength="20"
          />
        </view>
        
        <view class="form-item">
          <text class="form-label">手机号码</text>
          <input 
            class="form-input" 
            v-model="exchangeForm.phone" 
            placeholder="请输入手机号码"
            type="number"
            maxlength="11"
          />
        </view>
        
        <view class="form-item">
          <text class="form-label">收货地址</text>
          <textarea 
            class="form-textarea" 
            v-model="exchangeForm.address" 
            placeholder="请输入详细收货地址"
            maxlength="200"
          ></textarea>
        </view>
      </view>
      
      <view class="form-footer">
        <button 
          class="exchange-btn" 
          :class="{ 'btn-disabled': !canSubmit }"
          @tap="submitExchange"
          :disabled="!canSubmit"
        >
          <text class="exchange-text">{{ submitLoading ? '兑换中...' : '立即兑换' }}</text>
        </button>
      </view>
    </view>

    <!-- 兑换说明 -->
    <view class="card info-card">
      <view class="info-header">
        <text class="info-title">🎁 兑换说明</text>
      </view>
      <view class="info-content">
        <text class="info-item">• 累积{{ requiredCount }}次抽奖次数可兑换一份免费湿粮</text>
        <text class="info-item">• 兑换成功后抽奖次数将被清零</text>
        <text class="info-item">• 免费订单将在3-7个工作日内发货</text>
        <text class="info-item">• 每个用户每月最多兑换2次</text>
        <text class="info-item">• 请确保收货信息准确无误</text>
      </view>
    </view>

    <!-- 兑换记录 -->
    <view class="card record-card" v-if="exchangeRecords.length > 0">
      <view class="record-header">
        <text class="record-title">📦 兑换记录</text>
        <text class="record-count">共{{ exchangeRecords.length }}次</text>
      </view>
      <view class="record-list">
        <view 
          class="record-item" 
          v-for="(record, index) in exchangeRecords" 
          :key="index"
        >
          <view class="record-info">
            <text class="record-name">{{ record.name }}</text>
            <text class="record-phone">{{ record.phone }}</text>
            <text class="record-address">{{ record.address }}</text>
            <text class="record-time">{{ formatTime(record.createTime) }}</text>
          </view>
          <view class="record-status">
            <text 
              class="status-badge" 
              :class="getStatusClass(record.status)"
            >
              {{ getStatusText(record.status) }}
            </text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'

// 响应式数据
const totalLotteryCount = ref(0)
const requiredCount = ref(10) // 需要的抽奖次数
const submitLoading = ref(false)
const showHistoryModal = ref(false) // 抽奖历史弹窗显示状态
const lotteryHistory = ref([]) // 抽奖历史记录
const exchangeForm = ref({
  name: '',
  phone: '',
  address: ''
})
const exchangeRecords = ref([])

// 计算属性
const canExchange = computed(() => {
  return totalLotteryCount.value >= requiredCount.value
})

const progressPercentage = computed(() => {
  return Math.min((totalLotteryCount.value / requiredCount.value) * 100, 100)
})

const canSubmit = computed(() => {
  return (
    canExchange.value &&
    exchangeForm.value.name.trim() &&
    exchangeForm.value.phone.trim().length === 11 &&
    exchangeForm.value.address.trim() &&
    !submitLoading.value
  )
})

// 显示抽奖历史弹窗
const showLotteryHistory = () => {
  loadLotteryHistory()
  showHistoryModal.value = true
}

// 隐藏抽奖历史弹窗
const hideLotteryHistory = () => {
  showHistoryModal.value = false
}

// 跳转到兑换页面（这里可以是一个独立的兑换页面）
const goToExchange = () => {
  // 由于当前页面就包含兑换功能，可以滚动到兑换区域
  uni.pageScrollTo({
    selector: '.progress-card',
    duration: 300
  })
}

// 跳转到订单列表
const goToOrderList = () => {
  uni.navigateTo({
    url: '/pages/order/list'
  })
}

// 跳转到地址列表
const goToAddressList = () => {
  uni.navigateTo({
    url: '/pages/address/address'
  })
}

// 加载兑换数据
const loadExchangeData = async () => {
  try {
    // 这里应该调用后端API获取兑换配置
    // const res = await api.getExchangeConfig()
    // requiredCount.value = res.data.requiredCount
    
    loadTotalLotteryCount()
    loadExchangeRecords()
    loadLotteryHistory()
  } catch (error) {
    console.error('加载兑换数据失败:', error)
  }
}

// 加载总抽奖次数
const loadTotalLotteryCount = () => {
  // 这里应该调用后端API获取用户总抽奖次数
  // const res = await api.getTotalLotteryCount()
  // totalLotteryCount.value = res.data.totalCount
  
  // 临时使用本地存储模拟
  totalLotteryCount.value = uni.getStorageSync('totalLotteryCount') || 0
}

// 加载兑换记录
const loadExchangeRecords = () => {
  exchangeRecords.value = uni.getStorageSync('exchangeRecords') || []
}

// 加载抽奖历史
const loadLotteryHistory = () => {
  // 这里应该调用后端API获取抽奖历史
  // const res = await api.getLotteryHistory()
  // lotteryHistory.value = res.data.records
  
  // 临时使用本地存储模拟
  const history = uni.getStorageSync('lotteryHistory') || []
  // 如果没有历史记录，创建一些模拟数据
  if (history.length === 0) {
    const mockHistory = [
      { prize: '抽奖次数 +1', type: '次数', time: Date.now() - 86400000 },
      { prize: '湿粮试用装', type: '实物', time: Date.now() - 172800000 },
      { prize: '谢谢参与', type: '空奖', time: Date.now() - 259200000 },
      { prize: '抽奖次数 +2', type: '次数', time: Date.now() - 345600000 },
      { prize: '优惠券 5元', type: '优惠券', time: Date.now() - 432000000 }
    ]
    uni.setStorageSync('lotteryHistory', mockHistory)
    lotteryHistory.value = mockHistory
  } else {
    lotteryHistory.value = history
  }
}

// 获取奖品类型样式类
const getPrizeClass = (type) => {
  const classMap = {
    '次数': 'prize-count',
    '实物': 'prize-physical',
    '优惠券': 'prize-coupon',
    '空奖': 'prize-empty'
  }
  return classMap[type] || 'prize-default'
}

// 提交兑换
const submitExchange = async () => {
  if (!canSubmit.value) return
  
  submitLoading.value = true
  
  try {
    // 调用后端API提交兑换申请
    // const res = await api.submitExchange(exchangeForm.value)
    
    // 模拟提交
    const result = await mockSubmitExchange()
    
    submitLoading.value = false
    
  } catch (error) {
    console.error('提交兑换失败:', error)
    submitLoading.value = false
    uni.showToast({
      title: '提交失败，请重试',
      icon: 'none'
    })
  }
}

// 模拟提交兑换
const mockSubmitExchange = () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      // 创建兑换记录
      const record = {
        id: Date.now(),
        name: exchangeForm.value.name,
        phone: exchangeForm.value.phone,
        address: exchangeForm.value.address,
        usedCount: requiredCount.value,
        status: 'pending', // pending: 处理中, shipped: 已发货, completed: 已完成
        createTime: Date.now()
      }
      
      // 添加到兑换记录
      exchangeRecords.value.unshift(record)
      saveExchangeRecords()
      
      // 清零抽奖次数
      uni.setStorageSync('totalLotteryCount', 0)
      uni.setStorageSync('lotteryCount', 0)
      totalLotteryCount.value = 0
      
      // 清空表单
      exchangeForm.value = {
        name: '',
        phone: '',
        address: ''
      }
      
      uni.showModal({
        title: '兑换成功',
        content: '您的免费订单已提交，我们将在3-7个工作日内发货，请注意查收！',
        showCancel: false
      })
      
      resolve(record)
    }, 2000)
  })
}

// 保存兑换记录
const saveExchangeRecords = () => {
  uni.setStorageSync('exchangeRecords', exchangeRecords.value)
}

// 获取状态样式类
const getStatusClass = (status) => {
  const classMap = {
    'pending': 'status-pending',
    'shipped': 'status-shipped',
    'completed': 'status-completed'
  }
  return classMap[status] || 'status-pending'
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    'pending': '处理中',
    'shipped': '已发货',
    'completed': '已完成'
  }
  return textMap[status] || '处理中'
}

// 格式化时间
const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 生命周期钩子
onLoad(() => {
  loadExchangeData()
})

onShow(() => {
  loadTotalLotteryCount()
})
</script>

<style scoped>
.my-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #FFF8E1 0%, #FFECB3 100%);
  padding-bottom: 100px;
}

/* 页面标题 */
.page-header {
  padding: 30px 20px 20px;
  text-align: center;
}

.page-title {
  display: block;
  font-size: 24px;
  font-weight: bold;
  color: #FFB800;
  margin-bottom: 8px;
}

.page-subtitle {
  display: block;
  font-size: 14px;
  color: #666;
}

/* 抽奖次数卡片 */
.lottery-card {
  margin: 20px 16px;
}

.lottery-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.lottery-title {
  font-size: 18px;
  font-weight: bold;
  color: #FFB800;
}

.history-btn {
  background: linear-gradient(135deg, #2196F3 0%, #1976D2 100%);
  color: white;
  border: none;
  border-radius: 20px;
  padding: 8px 16px;
  font-size: 12px;
  box-shadow: 0 2px 8px rgba(33, 150, 243, 0.3);
}

.history-text {
  color: white;
}

.lottery-content {
  text-align: center;
  padding: 20px 0;
}

.lottery-count {
  font-size: 48px;
  font-weight: bold;
  color: #FFB800;
  margin-right: 8px;
}

.lottery-unit {
  font-size: 20px;
  color: #999;
}

/* 功能菜单 */
.menu-card {
  margin: 20px 16px;
}

.menu-header {
  margin-bottom: 16px;
}

.menu-title {
  font-size: 18px;
  font-weight: bold;
  color: #FFB800;
}

.menu-list {
  
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #f5f5f5;
}

.menu-item:last-child {
  border-bottom: none;
}

.menu-icon {
  font-size: 24px;
  margin-right: 16px;
  width: 32px;
  text-align: center;
}

.menu-text {
  flex: 1;
  font-size: 16px;
  color: #333;
}

.menu-arrow-icon {
  font-size: 18px;
  color: #ccc;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
}

/* 抽奖历史弹窗 */
.lottery-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 12px;
  width: 80%;
  max-height: 70%;
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #f5f5f5;
}

.modal-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.modal-close {
  font-size: 24px;
  color: #999;
  cursor: pointer;
}

.modal-body {
  max-height: 400px;
  overflow-y: auto;
}

.history-list {
  padding: 0 20px;
}

.history-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #f5f5f5;
}

.history-item:last-child {
  border-bottom: none;
}

.history-info {
  flex: 1;
}

.history-prize {
  display: block;
  font-size: 16px;
  color: #333;
  margin-bottom: 4px;
}

.history-time {
  display: block;
  font-size: 12px;
  color: #999;
}

.history-status {
  
}

.prize-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

.prize-count {
  background: rgba(255, 184, 0, 0.1);
  color: #FFB800;
}

.prize-physical {
  background: rgba(76, 175, 80, 0.1);
  color: #4CAF50;
}

.prize-coupon {
  background: rgba(33, 150, 243, 0.1);
  color: #2196F3;
}

.prize-empty {
  background: rgba(158, 158, 158, 0.1);
  color: #9E9E9E;
}

.empty-history {
  text-align: center;
  padding: 40px 20px;
}

.empty-text {
  font-size: 14px;
  color: #999;
}

/* 进度卡片 */
.progress-card {
  margin: 20px 16px;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.progress-title {
  font-size: 18px;
  font-weight: bold;
  color: #FFB800;
}

.progress-desc {
  font-size: 12px;
  color: #999;
}

.progress-content {
  margin-bottom: 16px;
}

.progress-bar {
  width: 100%;
  height: 12px;
  background: #f0f0f0;
  border-radius: 6px;
  overflow: hidden;
  margin-bottom: 12px;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #FFB800 0%, #FF8F00 100%);
  border-radius: 6px;
  transition: width 0.3s ease;
}

.progress-text {
  text-align: center;
}

.current-count {
  font-size: 24px;
  font-weight: bold;
  color: #FFB800;
}

.separator {
  font-size: 20px;
  color: #ccc;
  margin: 0 8px;
}

.required-count {
  font-size: 20px;
  color: #999;
}

.progress-status {
  text-align: center;
}

.status-text {
  font-size: 16px;
  font-weight: bold;
}

.can-exchange {
  color: #4CAF50;
}

.cannot-exchange {
  color: #FF6B6B;
}

/* 兑换表单 */
.exchange-form-card {
  margin: 20px 16px;
}

.form-header {
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 2px solid #FFE082;
}

.form-title {
  font-size: 18px;
  font-weight: bold;
  color: #FFB800;
}

.form-content {
  margin-bottom: 24px;
}

.form-item {
  margin-bottom: 20px;
}

.form-label {
  display: block;
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
  font-weight: bold;
}

.form-input {
  width: 100%;
  padding: 12px 16px;
  border: 2px solid #FFE082;
  border-radius: 8px;
  font-size: 16px;
  background: white;
  transition: border-color 0.3s ease;
}

.form-input:focus {
  border-color: #FFB800;
}

.form-textarea {
  width: 100%;
  min-height: 80px;
  padding: 12px 16px;
  border: 2px solid #FFE082;
  border-radius: 8px;
  font-size: 16px;
  background: white;
  resize: none;
  transition: border-color 0.3s ease;
}

.form-textarea:focus {
  border-color: #FFB800;
}

.form-footer {
  
}

.exchange-btn {
  width: 100%;
  background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
  color: white;
  border: none;
  border-radius: 12px;
  padding: 16px;
  font-size: 18px;
  font-weight: bold;
  box-shadow: 0 4px 12px rgba(76, 175, 80, 0.3);
  transition: all 0.3s ease;
}

.exchange-btn:active {
  transform: translateY(2px);
  box-shadow: 0 2px 8px rgba(76, 175, 80, 0.3);
}

.btn-disabled {
  background: #ccc !important;
  box-shadow: none !important;
  transform: none !important;
}

.exchange-text {
  color: white;
}

/* 说明信息 */
.info-card {
  margin: 20px 16px;
}

.info-header {
  margin-bottom: 16px;
}

.info-title {
  font-size: 16px;
  font-weight: bold;
  color: #FFB800;
}

.info-content {
  
}

.info-item {
  display: block;
  font-size: 14px;
  color: #666;
  line-height: 24px;
  margin-bottom: 8px;
}

/* 兑换记录 */
.record-card {
  margin: 20px 16px;
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 2px solid #FFE082;
}

.record-title {
  font-size: 18px;
  font-weight: bold;
  color: #FFB800;
}

.record-count {
  font-size: 12px;
  color: #999;
}

.record-list {
  
}

.record-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 16px 0;
  border-bottom: 1px solid #f5f5f5;
}

.record-item:last-child {
  border-bottom: none;
}

.record-info {
  flex: 1;
}

.record-name {
  display: block;
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
}

.record-phone {
  display: block;
  font-size: 14px;
  color: #666;
  margin-bottom: 4px;
}

.record-address {
  display: block;
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
  line-height: 20px;
}

.record-time {
  display: block;
  font-size: 12px;
  color: #999;
}

.record-status {
  
}

.status-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

.status-pending {
  background: rgba(255, 184, 0, 0.1);
  color: #FFB800;
}

.status-shipped {
  background: rgba(33, 150, 243, 0.1);
  color: #2196F3;
}

.status-completed {
  background: rgba(76, 175, 80, 0.1);
  color: #4CAF50;
}
</style>